<template>
  <div>
    <!-- TableModule  tableModule是一个对象，下面有解释 -->
    <TableModule :tableModule="tableModule" ref="TableModuleRef">
      <!-- #event是插入的新增按钮和删除按钮，具体操作按照自己的业务流程实现 -->
      <template #event>
        <el-button type="primary" @click="Add">新增</el-button>
        <el-popconfirm
          :title="`已勾选${multipleSelection.length}条记录，你确定要删除吗?`"
          hide-icon
          confirm-button-type="danger"
          @confirm="Delete"
        >
          <template #reference>
            <el-button type="danger" :disabled="!multipleSelection.length"
              >批量删除</el-button
            >
          </template>
        </el-popconfirm>
        <el-button>
          <el-link
            @click.stop.self
            :underline="false"
            href="https://minio.jiayekj.xyz/sziit-sport-bucket/demo-excel/members-info-demo.xlsx"
            >模板下载</el-link
          >
        </el-button>
        <el-button @click="batchVisible = true">批量添加</el-button>
      </template>
      <!-- #tableColumn 插入表格的操作列 -->
      <template #tableColumn>
        <el-table-column align="center" fixed="right" label="操作" width="100">
          <template slot-scope="scope" #default="scope">
            <el-button-group>
              <!-- <el-button @click="Edit(scope)">编辑</el-button> -->
              <el-popconfirm
                title="你确定要删除这个吗?"
                hide-icon
                confirm-button-type="danger"
                @confirm="DeleteOne(scope)"
              >
                <template #reference>
                  <el-button type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </el-button-group>
          </template>
        </el-table-column>
      </template>
    </TableModule>
  </div>
  <!-- 单个学生弹窗 -->
  <AddFormModule :addModule="addModule"></AddFormModule>
  <!-- 编辑信息弹窗 -->
  <!-- <EditFormModule :editModule="editModule"></EditFormModule> -->

  <!-- 批量添加 -->
  <el-dialog v-model="batchVisible" title="批量添加" width="500">
    <!-- <el-upload
      class="mx-3"
      :action="actionUrl + '/admin/team/members/import'"
      :headers="{ Authorization: getToken() }"
      :show-file-list="false"
      accept=".xls,.xlsx"
      :on-success="handleExcelSuccess"
    >
      <el-button>批量添加</el-button>
    </el-upload> -->
    <el-upload
      class="upload-demo"
      :action="actionUrl + '/admin/team/members/import'"
      :headers="{ Authorization: getToken() }"
      :show-file-list="false"
      accept=".xls,.xlsx"
      :on-success="handleExcelSuccess"
      drag
      multiple
    >
      <el-icon class="el-icon--upload"><upload-filled /></el-icon>
      <div class="el-upload__text">将文件放到这里或<em>点击上传</em></div>
    </el-upload>
  </el-dialog>
</template>

<script setup>
import TableModule from "@/components/TableModule.vue";
import AddFormModule from "@/components/AddFormModule.vue";
// import EditFormModule from "@/components/EditFormModule.vue";
import { reactive, toRefs, ref, onMounted, toRaw, watch } from "vue";
import { getToken } from "@/utils/auth.js";
import { toast, generateAcademicYears } from "@/utils";
import {
  columnsData,
  queryData,
  addData,
  // editData
} from "./table"; // 引入我们配置好的数据
import {
  getAllList,
  addInfo,
  deleteInfo,
  // updateInfo
} from "@/api/members.js";
import { getTermslist, getTermsnoids } from "/src/api/team.js";

const props = defineProps({
  height: Number,
});
const actionUrl = import.meta.env.DEV
  ? "/api"
  : import.meta.env.VITE_APP_BASEURL;
const batchVisible = ref(false);
const state = reactive({
  columns: columnsData, // 表格配置
  query: queryData, // 查询条件配置
  queryForm: {}, // 查询form表单
  addVisible: false, //新增表单弹窗
  addTitle: "新增人员", //新增表单标题
  add: addData, //新增表单配置
  addForm: {}, //新增form表单
  // editVisible: false,
  // edit: editData, //编辑表单配置
  // editTitle: "",
  // editForm: {}, //编辑表单
  loading: false, // 加载状态
  dataList: [], // 列表数据
  multipleSelection: [], //多选数组
  rowIndex: 0, // 行索引 用于可编辑单元格
  columnIndex: 0, // 列索引 用于可编辑单元格
  height: 0,
  pages: {
    // 分页数据
    total: 0,
    limit: 10,
    page: 1,
  },
});

const {
  loading,
  dataList,
  columns,
  pages,
  query,
  queryForm,
  addVisible,
  addTitle,
  add,
  addForm,
  // editVisible,
  // editTitle,
  // edit,
  // editForm,
  multipleSelection,
  rowIndex,
  columnIndex,
  height,
} = toRefs(state);

const TableModuleRef = ref();

onMounted(() => {
  setTimeout(() => {
    state.height = props.height;
  }, 100);
  // console.log(`output->`, state.query[0].options[0].teamId);
  // state.queryForm.teamId = state.query[0].options[0].teamId;
  getDataList();
});

// 传给表格子组件的
const tableModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: getDataList, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  selectcallback: selectChange,
  // 以下不说了，上面都给解释了
  queryForm: queryForm,
  query: query,
  columns: columns,
  dataList: dataList,
  multipleSelection: multipleSelection,
  rowIndex: rowIndex,
  columnIndex: columnIndex,
  height: height,
  loading: loading,
  pages: pages,
});

// 传给新增表单子组件的
const addModule = ref({
  editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
  callback: addInfoData, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
  selectcallback: addChange,
  // 以下不说了，上面都给解释了
  addForm: addForm,
  addTitle: addTitle,
  add: add,
  addVisible: addVisible,
});

// 传给新增表单子组件的
// const editModule = ref({
//   editInputBlur: editInputBlur, // 可编辑单元的，失去焦点时的回调
//   callback: editInfoData, // 回调，子组件中可以看到很多调用callback的，这里对应的是获取列表数据的方法
//   // 以下不说了，上面都给解释了
//   editForm: editForm,
//   editTitle: editTitle,
//   edit: edit,
//   editVisible: editVisible,
// });

//查询表单值变化
async function selectChange(porp) {}

//监测查询运动队条件改变查询学年选项
watch(
  () => state.queryForm.teamId,
  async (newValue, oldValue) => {
    console.log(`output->teamId`, newValue);
    if (newValue) {
      const { data } = await getTermslist({ teamId: newValue });
      if (data.length > 0) {
        console.log(`output->res`, data);
        state.query[1].options = data;
        state.queryForm.term = data[0];
      }
    } else {
      state.query[1].options = [];
      state.queryForm.term = null;
    }
  }
);

//新增表单值变化
async function addChange(prop) {
  console.log(`output->addChange`, prop);
  if (prop == "teamId") {
    const teamWithIdOne = state.add[0].options.find(
      (team) => team.teamId === state.addForm.teamId
    );
    const foundedDate = new Date(
      teamWithIdOne ? teamWithIdOne.foundedDate : null
    ).getFullYear();
    const terms = generateAcademicYears(foundedDate).reverse();
    state.add[1].options = terms;
    state.addForm.term = terms[0];
  }
}

//监测新增类型条件改变新增人员选项
watch(
  () => state.addForm.type,
  async (newValue, oldValue) => {
    if (state.addForm.teamId && state.addForm.term && state.addForm.type) {
      let params = {
        teamId: state.addForm.teamId,
        term: state.addForm.term,
        type: state.addForm.type,
      };
      const { data } = await getTermsnoids(params);
      state.add[3].options = data;
    } else {
      state.add[3].options = [];
    }
  }
);

// 获取列表信息
async function getDataList() {
  state.loading = true;
  //参数
  let params = {
    pageNum: state.pages.page,
    pageSize: state.pages.limit,
  };
  if (state.queryForm.type) {
    params.type = state.queryForm.type;
  }
  if (state.queryForm.term) {
    params.term = state.queryForm.term;
  }
  if (state.queryForm.teamId) {
    params.teamId = state.queryForm.teamId;
  }
  // 掉自己的接口，切勿复制粘贴
  const res = await getAllList(params);
  if (res.code == 200) {
    console.log(`output->res`, res);
    toast("获取成功");
    state.dataList = res.data.records;
    state.pages.total = res.data.total;
  } else {
    console.log(`output->error`, res);
    toast(res.msg ? res.msg : "获取失败", "error");
  }
  state.loading = false;
}

// 点击新增触发弹窗
function Add() {
  state.addForm.type = "";
  addVisible.value = true;
  state.addForm = {
    teamId: state.queryForm.teamId,
    term: state.queryForm.term,
    type: state.queryForm.type,
    userIdList: [],
  };
}

//新增信息
async function addInfoData() {
  state.loading = true;
  let data = {
    teamId: state.addForm.teamId,
    term: state.addForm.term,
    userIdList: state.addForm.userIdList,
    type: state.addForm.type,
  };
  const res = await addInfo(data);
  if (res.code == 200) {
    console.log(`output->addInfoData`, res);
    toast(res.data ? res.data : "添加失败");
    addVisible.value = false;
    setTimeout(getDataList(), 100);
  } else {
    console.log(`output->addInfoData`, res);
    toast(res.msg ? res.msg : "添加失败", "error");
  }
  state.loading = false;
}

// function Edit(row) {
//   // 编辑事件
//   // console.log(`output->编辑事件`, toRaw(row.row));
//   state.editVisible = true;
//   state.editTitle = "修改 " + toRaw(row.row).name + " 的信息";
//   state.editForm = toRaw(row.row);
// }

//修改信息
// async function editInfoData() {
//   // console.log(`output->`, state.editForm);
//   const res = await updateInfo(state.editForm);
//   // console.log(`output->addInfoData`, res);
//   if (res.code == 200) {
//     toast(res.data);
//     editVisible.value = false;
//     getDataList();
//   } else {
//     toast(res.data, "error");
//   }
// }

// 单个删除事件
async function DeleteOne(row) {
  state.loading = true;
  // console.log(`output->单个删除事件`, toRaw(row.row));
  //参数
  let params = {
    teamId: state.queryForm.teamId,
    term: state.queryForm.term,
    userId: toRaw(row.row).userId,
  };
  const res = await deleteInfo(params);
  if (res.code == 200) {
    toast("删除成功");
    setTimeout(getDataList(), 100);
  } else {
    toast("删除失败", "error");
  }
  state.loading = false;
}

function Delete() {
  // 删除事件
  state.loading = true;
  let code = true;
  toRaw(state.multipleSelection).forEach(async (item) => {
    console.log(`output->Delete`, item);
    //参数
    let params = {
      teamId: state.queryForm.teamId,
      term: state.queryForm.term,
      userId: item.userId,
    };
    const res = await deleteInfo(params);
    if (res.code != 200) code = false;
  });
  if (code) {
    toast("删除成功");
    setTimeout(getDataList(), 100);
  } else {
    toast("删除失败", "error");
  }
  state.loading = false;
}

function editInputBlur() {
  console.log("失去焦点回调");
}

//xlsx批量添加
async function handleExcelSuccess(res, file) {
  if (res.code == 200) {
    console.log(`output->handleExcelSuccess`, res);
    toast(res.data ? res.data : "添加成功");
    setTimeout(getDataList(), 100);
  } else {
    console.log(`output->handleExcelSuccess`, res);
    toast(res.msg ? res.msg : "添加失败", "error");
  }
  batchVisible.value = false;
}
</script>

<style scoped></style>
